package mylab.io.core.codec;

import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.UUID;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.logging.LogLevel;
import lombok.Getter;
import mylab.base.foundation.template.pojo.BaseStringIDPojo;
import mylab.io.base.model.Msg;
import mylab.io.base.property.DasProperties;
import mylab.io.core.context.CoreContext;
import mylab.io.core.util.HandlerUtil;


public abstract class AbstractCodec<P extends DasProperties, M extends Msg, F>
        extends BaseStringIDPojo
        implements Codec<P, M, F> {

    @Getter
    @JsonIgnore
    protected CoreContext<P, M> context;

    @Getter
    @JsonIgnore
    protected P properties;

    @Getter
    @JsonIgnore
    protected MsgResolver<M, F> resolver;

    @JsonIgnore
    protected Channel channel;

    public AbstractCodec(CoreContext<P, M> context, MsgResolver<M, F> resolver) {
        this.id = UUID.randomUUID().toString();
        this.name = getClass().getSimpleName();
        this.context = context;
        this.properties = context.getDasPropertites();
        this.resolver = resolver;
    }

    @Override
    public ChannelInitializer<Channel> getChannelInitializer() {
        return new ChannelInitializer<>() {
            @Override
            protected void initChannel(Channel channel) throws Exception {
                context.initChannel(channel);
                initPipeLine(channel);
            }
        };
    }

    @Override
    public void initPipeLine(Channel channel) throws Exception {
        this.channel = channel;
        DasProperties dasProperties = getContext().getDasPropertites();

        channel.pipeline().addLast(HandlerUtil.HANDLER_NAME_IDLE_STATE, HandlerUtil.newIdleStateHandler(dasProperties.getCommon().getIdle()));
        channel.pipeline().addLast(HandlerUtil.HANDLER_NAME_LOG, HandlerUtil.newLoggingHandler(LogLevel.INFO));
    }

}
